package cc.ufinity.networkdiagnose.widget;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cc.ufinity.networkdiagnose.chart.ChartManager;
import cc.ufinity.networkdiagnose.manager.FtpTestManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.Task.FTPTask;
import cc.ufinity.networkdiagnose.view.R;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class FtpTestProxyWidget extends GeneralTestWidget {

	private Activity ctx;
	private FtpTestManager ftm;
	private LinearLayout ftpTestChartLayout;
	private Button backBtn;
	private ScrollView scrView;
	private LinearLayout ftpTestDetail;
	private Task task;
	private FTPTask ftpTask;
	private Handler ftpTestHandler;
	private String localFilePath = Environment.getExternalStorageDirectory()+ "/ftptest/";
	private String remotePath = "/";
	private String fileName = "ftp_test.png";
	private int taskSize;
	private boolean taskProcessing;
	private int currentTaskNum;
	private int testedTimes;
	private List<double[]> tmpUpYdatas;
	private List<double[]> tmpDwYdatas; 
	private int testFlag = 0;
	// private static final int COUNT = 3;
	private static final String TAG = "ftpTest";

	public FtpTestProxyWidget(Activity context) {
		super(context);
		this.ctx = context;
		inflate(ctx, R.layout.ftp_test_proxy_widget, this);
		ftpTestChartLayout = (LinearLayout) this
				.findViewById(R.id.ftpTestProxyChartLayout);
		backBtn = (Button) this.findViewById(R.id.ftp_test_proxy_btnback);
		scrView = (ScrollView) this.findViewById(R.id.ftp_test_proxy_ScrView);
		ftpTestDetail = (LinearLayout) this
				.findViewById(R.id.ftp_test_proxy_detail);
		backBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				backToTask(ctx);
			}
		});
		ftpTestHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.FTP_UPLOAD_DONE:
					updateUploadProgress();
					break;
				case MessageWhat.FTP_DOWNLOAD_DONE:
					updateDownloadProgress();
					break;
				case MessageWhat.DONE:
					updateTestResult();
					mSendBroadcast(ctx);
					break;
				case MessageWhat.FTP_CONNECT_TIMEOUT:
					dismissProgressDialog();
					taskProcessing = false;
					showMessage(ctx, "FTP连接超时.");
					break;
				case MessageWhat.DO_NEXT_TEST:
					doPingTest();
					break;
				}
			}
		};

		ftm = new FtpTestManager(localFilePath, remotePath, fileName);
		ftm.setHandler(ftpTestHandler);
		statFtpTest();
	}
	public void mSendBroadcast(Activity activity) {
		Intent intent = new Intent();
		intent.setAction("doNext");
		intent.putExtra("testIndex",TAG+String.valueOf(testFlag++));
		activity.sendBroadcast(intent);
	}
	private void doPingTest() {
		PingWidgetProxy ping = new PingWidgetProxy(ctx);
		//ctx.setContentView(ping);
	}

	private void doNextTest() {
		TimerTask timerTask = new TimerTask() {
			@Override
			public void run() {
				ftm.sendMsg(MessageWhat.DO_NEXT_TEST);
			}
		};
		Timer t = new Timer();
		t.schedule(timerTask, TASK_PERFORM_INTERVAL);
	//	this.showMessage(ctx, "FTP测试已完成，10秒后进入下一项测试");
	}

	private void initTestData() {
		String path = "cc/ufinity/networkdiagnose/widget/ftp_test.png"; // 图片存放的路径
		InputStream is = ctx.getClassLoader().getResourceAsStream(path); // 得到图片流
		// FileInputStream fis = new FileInputStream(is);
		try {
			ftm.setFileSize(is.available());
			File f = new File(localFilePath);
			if (!f.exists()) {
				f.mkdirs();
			}
			FileOutputStream os = new FileOutputStream(localFilePath + fileName);
			byte[] buffer = new byte[512];
			int ch = -1;
			while ((ch = is.read(buffer)) != -1) {
				os.write(buffer, 0, ch);
			}
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void updateUploadProgress() {
		testedTimes ++;
		this.setDialogProgress(testedTimes);
		DecimalFormat df = new DecimalFormat("#");
		float uploadSpeed = ftm.getCurrentUpSpeed();
		int time = ftm.getCurrentTimes();
		StringBuffer sb = new StringBuffer();
		sb.append("第").append(time).append("次"+ftpTask.address+"上传速度为：")
				.append(df.format(uploadSpeed));
		sb.append("KB/S");
		TextView tv = new TextView(ctx);

		tv.setTextSize(12);
		tv.setText(sb.toString());
		ftpTestDetail.addView(tv);
		ftm.setTesting(false);
		setScrollViewDown(scrView);
	}

	private void updateDownloadProgress() {
		testedTimes ++;
		this.setDialogProgress(testedTimes);
		DecimalFormat df = new DecimalFormat("#");
		float dwSpeed = ftm.getCurrentDwSpeed();
		int time = ftm.getCurrentTimes();
		StringBuffer sb = new StringBuffer();
		sb.append("第").append(time).append("次"+ftpTask.address+"下载速度为：")
				.append(df.format(dwSpeed));
		sb.append("KB/S");
		TextView tv = new TextView(ctx);
		tv.setTextSize(12);
		tv.setText(sb);
		ftpTestDetail.addView(tv);
		ftm.setTesting(false);
		setScrollViewDown(scrView);
	}

	private void updateTestResult() {
		DecimalFormat df = new DecimalFormat("#");
		float totalUpSpeed = ftm.getTotalUpSpeed();
		float totalDwSpeed = ftm.getTotalDwSpeed();
		int frequency = ftm.getFrequency();
		float avgUpRate = totalUpSpeed / frequency;
		float avgDwRate = totalDwSpeed / frequency;
		ftpTask.loginTime = ftm.getLoginTime();
		ftpTask.downRate = df.format(avgDwRate);
		ftpTask.upRate = df.format(avgUpRate);
		task.ftpTasks.set(currentTaskNum-1, ftpTask);
		ctx.getIntent().putExtra(TAG_REFER_TASK, task);
		StringBuffer s = new StringBuffer();
		s.append("总次数:").append(frequency * 2);
		s.append(" 平均上载速度：").append(df.format(avgUpRate)).append(" kb/s");
		s.append(" 平均下载速度：").append(df.format(avgDwRate)).append(" kb/s");
		TextView tv = new TextView(ctx);
		tv.setTextColor(Color.CYAN);
		tv.setTextSize(13);
		tv.setText(s);
		ftpTestDetail.addView(tv);
		setScrollViewDown(scrView);
		//finished one task
		tmpUpYdatas.add(ftm.getUpY());
		tmpDwYdatas.add(ftm.getDwY());
		taskProcessing = false;
		ftm.setTesting(false);
		ftm.currentTimes = 0;
		if(currentTaskNum == taskSize){
			drawLineChart();
			dismissProgressDialog();
			doNextTest();
		}
	}

	public void statFtpTest() {
		task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);
		final List<FTPTask> tasks = task.ftpTasks;
		taskSize = tasks.size();
//		this.showProgressDialog(ctx, "正在进行FTP测试...", task.testCount*taskSize*2);
		tmpUpYdatas = new ArrayList<double[]>(taskSize);
		tmpDwYdatas = new ArrayList<double[]>(taskSize); 
		new Thread() {
			public void run() {
				initTestData();
				while (currentTaskNum < taskSize) {
					if (!taskProcessing) {
						taskProcessing = true;
						ftpTask = tasks.get(currentTaskNum);
						currentTaskNum ++;
						if (ftm.login(ftpTask.address, 21, ftpTask.user,
								ftpTask.pwd)) {
							ftm.startFtpUpTest(task.testCount);
							try {
								Thread.sleep(500);
							} catch (InterruptedException e) {
								Log.e(TAG, "FTP测试线程等待出错：", e);
							}
							ftm.startFtpDwTest(task.testCount);
						} else {
							ftm.sendMsg(MessageWhat.FTP_CONNECT_TIMEOUT);
						}
					}
				}
			}
		}.start();
	}

	private void drawLineChart() {
		ctx.getIntent().putExtra(TAG_REFER_TASK, task);
		int length = taskSize*task.testCount;
		double[] xdatas = new double[length];
		double[] upYdatas = new double[length];
		double[] dwYdatas = new double[length];
		for(int i=0;i<length;i++){
			xdatas[i] = i+1;
		}
		int isize = tmpUpYdatas.size();
		for (int i = 0; i < isize; i++) {
			double[] tYdata = tmpUpYdatas.get(i);
			int len = tYdata.length;
			System.arraycopy(tYdata, 0, upYdatas, i * len, len);
		}
		isize = tmpDwYdatas.size();
		for (int i = 0; i < isize; i++) {
			double[] tYdata = tmpDwYdatas.get(i);
			int len = tYdata.length;
			System.arraycopy(tYdata, 0, dwYdatas, i * len, len);
		}
		ChartManager cm = new ChartManager(ctx, 5, 500);
		String chartTitle = "FTP上传/下载测试";
		String[] lineTitles = new String[] { "FTP上传测试", "FTP下载测试" };
		List<double[]> x = new ArrayList<double[]>(2);
		List<double[]> y = new ArrayList<double[]>(2);
//		x.add(ftm.getUpX());
//		y.add(ftm.getUpY());
//		x.add(ftm.getDwX());
//		y.add(ftm.getDwY());
		x.add(xdatas);
		y.add(upYdatas);
		x.add(xdatas);
		y.add(dwYdatas);
		int[] colors = new int[] { Color.YELLOW, Color.GREEN };
		View lineChart = cm.createLineChart(colors, chartTitle, lineTitles, x,
				y);
		ftpTestChartLayout.addView(lineChart, new LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
	}
/*	public static int getTestFlag() {
		return testFlag;
	}
	public static void setTestFlag(int testFlag) {
		FtpTestProxyWidget.testFlag = testFlag;
	}*/

}
